package com.softa.web.controller.system;

import com.softa.exception.BusinessException;
import com.softa.service.test.TestService;
import com.softa.web.controller.base.BaseController;
import com.softa.test.ValidateTest;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by yangl on 2016/12/28.
 */
@RestController
@RequestMapping("/test")
public class TestController extends BaseController {

    @Resource
    private TestService testService;

    @RequestMapping(value = "/validate", method = RequestMethod.POST)
    public Map<String, String> validate(@Valid @NotNull(message = "validateTest不能为空") ValidateTest validateTest, BindingResult result) {
        Map<String, String> map = new HashMap<String, String>();
        if(result.hasErrors()){
            map = getErrors(result);
        }else{
            map.put("status", "成功");
        }
        return map;
    }

    @RequestMapping(value = "/validate2", method = RequestMethod.POST)
    public Map<String, String> validate2(ValidateTest validateTest) throws BusinessException {
        Map<String, String> map = new HashMap<String, String>();
        map.put("status", "成功");
        testService.testValidate(validateTest);
        return map;
    }

    private Map<String, String> getErrors(BindingResult result) {
        Map<String, String> map = new HashMap<String, String>();
        List<FieldError> list = result.getFieldErrors();
        for (FieldError error : list) {
            System.out.println("error.getField():" + error.getField());
            System.out.println("error.getDefaultMessage():" + error.getDefaultMessage());
            map.put(error.getField(), error.getDefaultMessage());
        }
        return map;
    }

}
